import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

import { validate } from '@/service/base';

// 异步actions
// 更新store中用户的信息，可以用来更新用户store中的权限信息
export const updateUserInfo = createAsyncThunk('common/updateUserInfo', (status=true) => validate());

// common store
const initialState = {
    userInfo: {},
    roleInfo: [],
    permissionInfo: [],
    loginVisible: false,
    bindVisible: false,
    bindType: '',
    serviceVisible: false,
    noticeVisible: false,
    activeVisible: false,
    payVisible: false,
    reportVisible: false,
    reportTarget: {},
    feedbackVisible: false,

    sideCollapsed: false,
};

const common = createSlice({
    name: 'common',
    initialState,
    reducers: {
        reset: (state, action) => {
            for(let key in initialState) {
                state[key] = initialState[key];
            }
        },
        setStore: (state, action) => {
            for(let key in action.payload) {
                state[key] = action.payload[key];
            }
        },
    },
    extraReducers: (builder) => {
        builder.addCase(updateUserInfo.pending, (state, action) => {}).
            addCase(updateUserInfo.fulfilled, (state, action) => {
                let response = action.payload || {};
                if(OK_CODE === response?.code) {
                    state.userInfo = response?.data || {};
                }
            }).
            addCase(updateUserInfo.rejected, (state, action) => {});
    },
});

// 同步action
export const { reset, setStore } = common.actions;
// 异步action
export default common.reducer;